/**
 * 
 */

var updateErrors= new Array();
updateErrors["FIRSTNAME_BLANK"] = { divPos: "firstName", msj: "Complete el nombre" };
updateErrors["LASTNAME_BLANK"] = { divPos: "lastName", msj: "Complete los apellidos" };
updateErrors["EMAIL_BLANK"] = { divPos: "email", msj: "Complete el email" };
updateErrors["EMAIL_INCORRECT"] = { divPos: "email", msj: "El email tiene un formato incorrecto" };
updateErrors["VEHICLETYPE_BLANK"] = { divPos: "vehicleType", msj: "Complete el tipo de vehículo" };
updateErrors["GPSFETCHTIME_BLANK"] = { divPos: "fetchGpsLapseTime", msj: "Complete el intervalo de envío de datos GPS" };
updateErrors["GPSFETCHTIME_INCORRECT"] = { divPos: "fetchGpsLapseTime", msj: "El intervalo de envío de datos GPS tiene un formato incorrecto" };
updateErrors["GPSFETCHTIME_TOOBIG"] = { divPos: "fetchGpsLapseTime", msj: "El intervalo de envío de datos GPS es demasiado alto. Debe encontrarse entre 1000 y 5000 milisegundos" };
updateErrors["GPSFETCHTIME_TOOSMALL"] = { divPos: "fetchGpsLapseTime", msj: "El intervalo de envío de datos GPS es demasiado bajo. Debe encontrarse entre 1000 y 5000 milisegundos" };
updateErrors["OLDPASSWORD_BLANK"] = { divPos: "password", msj: "Complete la contraseña actual" };
updateErrors["OLDPASSWORD_INCORRECT"] = { divPos: "password", msj: "Contraseña actual incorrecta" };
updateErrors["NEWPASSWORD_BLANK"] = { divPos: "password1", msj: "Complete la contraseña" }; 
updateErrors["NEWPASSWORD_PERSONALDATAINCLUDED"] = { divPos: "password1", msj: "La contraseña incluye datos personales que la hacen poco segura" };
updateErrors["NEWPASSWORD_TOOSHORT"] = { divPos: "password1", msj: "La contraseña es demasiado corta. Debe terne al menos 8 caracteres" };
updateErrors["NEWPASSWORDS_UNMATCHED"] = { divPos: "password2", msj: "Las contraseñas no coinciden" };
updateErrors["NEWPASSWORD_CARACTERSNOTALLOWED"] = { divPos: "password1", msj: "La contraseña contiene caracteres no permitidos" };
updateErrors["NEWPASSWORD_CARACTERSNOTMIXED"] = { divPos: "password1", msj: "La contraseña debe contener al menos tres de los tipos de caracteres siguientes: letras minúsculas, letras mayúsculas, dígitos y caracteres speciales (coma, punto, guión, subrayado, almohadilla)" };

var markerIconNormal = '../images/gps-dot.png';
var markerIconCross = '../images/gps-pointer.png';
var markerIconOnSite = 'http://maps.google.com/mapfiles/ms/icons/red-dot.png';
var animationMarkerIconOnSite = 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png';
var mapEmulationData;
var mapEmulationMarkers;
var mapInitLat = 40.417343;
var mapInitLon = -3.703317;
var mapInitZoom = 17;

var fetchGpsLapseTime = 0;

$(document).ready(function() {

	loadMapsScript();
	initializeEmulationInitTime();
	
	//actualizar la informacion del usuario
	updateUserData();
	
	$("#btn-user-logout").click(function() {
		logoutUser();
	});
	
	$("#btn-user-update-do").click(function() {
		storeUserData();
	});
	
	$("#btn-user-update-cancel").click(function() {
		updateUserData();
	});
	
	$("#btn-user-updatepwd-do").click(function() {
		updateUserPassword();
	});
	
	$("#btn-gps-emulator-send-data").click(function() {
		storeEmulationGpsData();
	});
	
	$("#btn-gps-emulator-clear-data").click(function() {
		clearEmulationGpsData();
	});
	
});

function updateUserData() {
	var userId = $.getCookie("geoserverudima.userId");
	var sessionToken = $.getCookie("geoserverudima.sessionToken");
	
	$.ajax({
		url : "../rest/users",
	    type: "POST",
	    contentType: "application/json",
	    dataType: "json",
	    data : JSON.stringify({
		    	"userId": userId,
		    	"userSession": {"userId": userId, "sessionToken": sessionToken} 
	    	}),
	    success: function(data, textStatus, jqXHR) {
	    	if(processSessionErrors(data)) {
	    		paintHelloHeader(data.user);
		    	paintUserData(data.user);
	    	}
	    },
	    error: function (jqXHR, textStatus, errorThrown) {
	 
	    }
	});
}

function paintHelloHeader(user) {
	$("#div-hello-user-text").html("Hola, " + user.firstName + " " + user.lastName + " (" + user.userName + ")");
}

function paintUserData(user) {
	$("[name=userName]").val(user.userName);
	$("[name=firstName]").val(user.firstName);
	$("[name=lastName]").val(user.lastName);
	$("[name=email]").val(user.email);
	$("[name=vehicleTypeStr]").val(user.vehicleType);
	$("[name=fetchGpsLapseTimeStr]").val(user.fetchGpsLapseTime);
	
	fetchGpsLapseTime = user.fetchGpsLapseTime;
}

function logoutUser() {
	
	if(confirm("Se dispone a desconectarse del sistema. ¿Desea continuar?")) {
	
		var userId = $.getCookie("geoserverudima.userId");
		var sessionToken = $.getCookie("geoserverudima.sessionToken");
		
		$.ajax({
		    url : "../rest/users/logout",
		    type: "POST",
		    contentType: "application/json",
		    dataType: "json",
		    data : JSON.stringify({ "userSession": {"userId": userId, "sessionToken": sessionToken} }),
		    success: function(data, textStatus, jqXHR) {
		        document.cookie = "geoserverudima.userId=''";
		        document.cookie = "geoserverudima.sessionToken=''";
		        window.location = "mobileEmulatorLogin.jsp";
		    },
		    error: function (jqXHR, textStatus, errorThrown) {
		 
		    }
		});
		
	}
}

function storeUserData() {
	var formData = $.formDataToArray($("#frmUpdateUser"));
	var userId = $.getCookie("geoserverudima.userId");
	var sessionToken = $.getCookie("geoserverudima.sessionToken");
	
	var req = JSON.stringify({
					"userSession": {
						"userId": userId, 
						"sessionToken": sessionToken
					},
					"user": formData 
				});
	
	$.ajax({
	    url : "../rest/users/update",
	    type: "POST",
	    contentType: "application/json",
	    data : req,
	    dataType: "json",
	    success: function(data, textStatus, jqXHR) {
	    	if(processSessionErrors(data)) {
	    		processUserStoreResult(data);
	    	}
	    },
	    error: function (jqXHR, textStatus, errorThrown) {
	 
	    }
	});
}

function processUserStoreResult(ulr) {
	$("[id ^= div-user-update-error]").hide();
	if(ulr.responseSuccessful){
		//TODO mostrar msj bonito
		updateUserData();
		alert("Datos grabados correctamente");
	} else {
		$.each(ulr.responseErrors, function(index, value) {
			var error = updateErrors[value];
			if(error != undefined) {
				$("#div-user-update-error-" + error.divPos).html(error.msj).show();
			} else {
				$("#div-user-update-error-unknown").html("Ha ocurrido un error desconocido en la validación de los datos [" + value + "].<br>Por favor, inténtelo de nuevo pasados unos minutos.").show();
			}
			
		});
	}
}

function updateUserPassword() {
	var formData = $.formDataToArray($("#frmUpdatePassword"));
	var userId = $.getCookie("geoserverudima.userId");
	var sessionToken = $.getCookie("geoserverudima.sessionToken");
	
	var req = JSON.stringify({
					"userSession": {
						"userId": userId, 
						"sessionToken": sessionToken
					},
					"user": formData 
				});
	$.ajax({
	    url : "../rest/users/changepwd",
	    type: "POST",
	    contentType: "application/json",
	    data : req,
	    dataType: "json",
	    success: function(data, textStatus, jqXHR) {
	    	if(processSessionErrors(data)) {
	    		processUpdateUserPasswordResult(data);
	    	}
	    },
	    error: function (jqXHR, textStatus, errorThrown) {
	 
	    }
	});
}

function processUpdateUserPasswordResult(ulr) {
	$("[id ^= div-user-update-error]").hide();
	if(ulr.responseSuccessful){
		updateUserData();
		$("[name=password]").val("");
		$("[name=newPassword]").val("");
		$("[name=newPasswordRepeated]").val("");
		alert("Datos grabados correctamente");
	} else {
		$.each(ulr.responseErrors, function(index, value) {
			var error = updateErrors[value];
			if(error != undefined) {
				$("#div-user-update-error-" + error.divPos).html(error.msj).show();
			} else {
				$("#div-user-update-error-unknown").html("Ha ocurrido un error desconocido en la validación de los datos [" + value + "].<br>Por favor, inténtelo de nuevo pasados unos minutos.").show();
			}
			
		});
	}
}

function processSessionErrors(response) {
	var successful = response.responseSuccessful;
	if(!successful) {
		if($.inArray('SESSION_NOT_EXISTS', response.responseErrors) >= 0 
			|| $.inArray('SESSION_EXPIRED', response.responseErrors) >= 0) {
			//TODO pintar mas bonitos los errores de sesion en la pagina destino
			alert(response.responseErrors);
			window.location = 'mobileEmulatorLogin.jsp';
		} else {
			successful = true;
		}
	}
	return successful;
}

function initializeMap() {
	mapEmulationData = [];
	mapEmulationMarkers = [];
	
	var mapOptions = {
		center : new google.maps.LatLng(mapInitLat, mapInitLon),
		disableDefaultUI: true,
		zoom : mapInitZoom,
		mapTypeId : google.maps.MapTypeId.ROADMAP,
		draggableCursor: 'url('+markerIconCross+'), default'
	};
	
	map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
	
	google.maps.event.addListener(map, 'click', function(event) {
	    addEmulationPosition(event.latLng);
	  });
}

function loadMapsScript() {
	var script = document.createElement("script");
	script.type = "text/javascript";
	script.src = "https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initializeMap";
	document.body.appendChild(script);
}


function addEmulationPosition(gpsCoords, dateTime) {
	var lat = gpsCoords.lat();
	var lon = gpsCoords.lng();
	
	var lastEmulationDateTime;
	if(mapEmulationData.length > 0) {
		lastEmulationDateTime = mapEmulationData[mapEmulationData.length - 1].fetchTime;
	} else {
		lastEmulationDateTime = readEmulationInitDateTime();
	};
	var actualEmulationDateTime = new Date(lastEmulationDateTime.getTime() + fetchGpsLapseTime);
	
	mapEmulationData.push({
		fetchTime: actualEmulationDateTime,
		lat: lat,
		lon: lon
	});
	
	var marker = new google.maps.Marker({
			position: new google.maps.LatLng(lat, lon),
			icon: markerIconNormal,
			map: map 
		});
	mapEmulationMarkers.push(marker);
	
	paintEmulationPositionData();
}

function paintEmulationPositionData() {
	var div = $("#div-gps-emulator-locations-data");
	if(mapEmulationData.length == 0) {
		div.html("No hay datos GPS");
		enableEmulationInitTimeFields();
	} else {
		div.html(buildGpsDataList(mapEmulationData));
		disableEmulationInitTimeFields();
	}
}

function buildGpsDataList(gpsData) {
	var s = '';
	
	for (var i in gpsData) {
		var o = gpsData[i];
		var ft = $.formatDateTime(new Date(o.fetchTime), true, true);
		
		s += '<div class="user-gps-data-row" gps-point="' + i + '">';
		s += ft;
		s += '<br>';
		s += '&nbsp;&nbsp;[' + o.lat + ' / ' + o.lon + ']';
		if(o.speedFromPrevious != undefined) {
			s += ' - ' + (new Number(o.distanceFromPrevious)).toFixed(3) + ' m';
			s += ' - ' + (new Number(o.speedFromPrevious)).toFixed(1) + ' km/h';
		}
		s += '</div>';
	}
	
	return s;
}

function initializeEmulationInitTime() {
	var id = $("#emulation-init-date");
	var it = $("#emulation-init-time");
	var now = new Date();
	id.val($.formatDate(now));
	it.val($.formatTime(now));
}

function readEmulationInitDateTime() {
	var res;
	var id = $("#emulation-init-date").val();
	var it = $("#emulation-init-time").val();
	res = $.stringToDateTime(id + " " + it + ":00,000");
	return res;
}

function enableEmulationInitTimeFields() {
	$("#emulation-init-date").removeAttr("disabled");
	$("#emulation-init-time").removeAttr("disabled");
}

function disableEmulationInitTimeFields() {
	$("#emulation-init-date").attr("disabled", "disabled");
	$("#emulation-init-time").attr("disabled", "disabled");
}

function clearEmulationGpsData() {
	initializeMap();
	paintEmulationPositionData();
}

function storeEmulationGpsData() {
	var userId = $.getCookie("geoserverudima.userId");
	var sessionToken = $.getCookie("geoserverudima.sessionToken");
	
	var req = JSON.stringify({
					"userSession": {
						"userId": userId, 
						"sessionToken": sessionToken
					},
					"gpsData": mapEmulationData 
				});
	
	$.ajax({
	    url : "../rest/gps/store",
	    type: "POST",
	    contentType: "application/json",
	    data : req,
	    dataType: "json",
	    success: function(data, textStatus, jqXHR) {
	    	if(processSessionErrors(data)) {
	    		processStoreGpsDataResult(data);
	    	}
	    },
	    error: function (jqXHR, textStatus, errorThrown) {
	 
	    }
	});
}

function processStoreGpsDataResult(ulr) {
	if(ulr.responseSuccessful){
		//TODO mostrar msj bonito
		alert("Datos grabados correctamente");
		clearEmulationGpsData();
	} else {
		$.each(ulr.responseErrors, function(index, value) {
			var error = updateErrors[value];
			if(error != undefined) {
				$("#div-emulation-gpsdata-store-error").html(error.msj).show();
			} else {
				$("#div-emulation-gpsdata-store-error").html("Ha ocurrido un error desconocido en la grabación de los datos [" + value + "].<br>Por favor, inténtelo de nuevo pasados unos minutos.").show();
			}
			
		});
	}
}